# 安装：pip3 install pyserial   //python3
import numpy as np
import serial
import serial.tools.list_ports
import time
import threading


com_rx_buf = ''				# 接收缓冲区
com_tx_buf = ''				# 发送缓冲区
port_list: list				# 可用串口列表
port_select: list			# 选择好的串口


# 无串口返回0，
# 返回可用的串口列表
def get_com_list():
    global port_list
    # a = serial.tools.list_ports.comports()
    # print(a)
    # port_list = list(serial.tools.list_ports.comports())
    port_list = serial.tools.list_ports.comports()
    return port_list


def set_com_port(n=0):
    global port_list
    global port_select
    port_select = port_list[n]
    return port_select.device


# 打开串口
def serial_open(n=0):
    global COMM
    serial_port = set_com_port(n)
    COMM = serial.Serial(serial_port, 115200, timeout=0.01)
    if COMM.isOpen():
        print(serial_port, "open success")
        return 0
    else:
        print("open failed")
        assert 0
        return 255


# 关闭串口
def serial_close():
    global COMM
    COMM.close()
    print(COMM.name + "closed.")


def set_com_rx_buf(buf=''):
    global com_rx_buf
    com_rx_buf = buf


def set_com_tx_buf(buf=''):
    global com_tx_buf
    com_tx_buf = buf


def get_com_rx_buf():
    global com_rx_buf
    return com_rx_buf


def get_com_tx_buf():
    global com_tx_buf
    return com_tx_buf


def thread_com_receive():
    while True:
        try:
            rx_buf = ''
            rx_buf = COMM.read()  # 转化为整型数字
            if rx_buf != b'':
                time.sleep(0.01)
                rx_buf = rx_buf + COMM.read_all()
                print("串口收到消息:", rx_buf)
            time.sleep(0.1)
        except:
            pass
    pass


Y0_ON = [0x02, 0x31, 0x31, 0x30, 0x31, 0x34, 0x30,
         0x32, 0x30, 0x30, 0x32, 0x32, 0x03, 0x32, 0x30]
Y0_OFF = [0x02, 0x31, 0x31, 0x30, 0x31, 0x34, 0x30,
          0x32, 0x30, 0x30, 0x31, 0x33, 0x03, 0x32, 0x30]
# 3.吸附：
Y1_ON = [0x02, 0x31, 0x31, 0x30, 0x31, 0x36, 0x30,
         0x32, 0x30, 0x30, 0x32, 0x32, 0x03, 0x32, 0x32]
# 4.吸附：
Y1_OFF = [0x02, 0x31, 0x31, 0x30, 0x31, 0x36, 0x30,
          0x32, 0x30, 0x30, 0x31, 0x33, 0x03, 0x32, 0x32]
# 5.释放：
Y2_ON = [0x02, 0x31, 0x31, 0x30, 0x31, 0x38, 0x30,
         0x32, 0x30, 0x30, 0x32, 0x32, 0x03, 0x32, 0x34]
# 6.释放
Y2_OFF = [0x02, 0x31, 0x31, 0x30, 0x31, 0x38, 0x30,
          0x32, 0x30, 0x30, 0x31, 0x33, 0x03, 0x32, 0x34]
# 7.
Y3_ON = [0x02, 0x31, 0x31, 0x30, 0x31, 0x32, 0x30,
         0x32, 0x31, 0x31, 0x32, 0x32, 0x03, 0x32, 0x30]
Y3_ON = [0x02, 0x31, 0x31, 0x30, 0x31, 0x32, 0x30,
         0x32, 0x31, 0x31, 0x33, 0x31, 0x03, 0x32, 0x30]
# 9.吸附完成：
SEND_Y4 = [0x02, 0x30, 0x31, 0x30, 0x31, 0x43, 0x30, 0x32, 0x03, 0x36, 0x41]
READ_Y4_OFF = [0x02, 0x30, 0x30, 0x30, 0x30, 0x03, 0x43, 0x33]
READ_Y4_ON = [0x02, 0x31, 0x31, 0x31, 0x31, 0x03, 0x43, 0x37]
# 10.释放完成
SEND_Y5 = [0x02, 0x30, 0x31, 0x30, 0x31, 0x45, 0x30, 0x32, 0x03, 0x36, 0x43]
READ_Y5_OFF = [0x02, 0x30, 0x30, 0x30, 0x30, 0x03, 0x43, 0x33]
READ_Y5_ON = [0x02, 0x31, 0x31, 0x31, 0x31, 0x03, 0x43, 0x37]


def list_to_hex_string(list_data):
    list_str = '[ '
    for x in list_data:
        list_str += '0x{:02X},'.format(x)
    list_str += ' ]'
    return list_str


global COMM
COMM = 1


def shifang():
    COMM.write(Y1_OFF)
    time.sleep(0.1)
    COMM.write(Y2_ON)
    time.sleep(0.15)
    _buf = COMM.read_all()
    while 1:
        COMM.write(SEND_Y5)
        time.sleep(1.05)
        _buf = COMM.read_all()
        # na=np.array(_buf,dtype=np.byte)
        print(len(_buf), _buf, bytes(READ_Y5_OFF),
              list_to_hex_string(list(_buf)))
        if _buf == b'\x820000\x03\xc33':
            print("e1")
            return 0


def xifu():
    COMM.write(Y2_OFF)
    time.sleep(0.1)
    COMM.write(Y1_ON)
    time.sleep(0.1)
    print(COMM.read_all())
    while 1:
        COMM.write(SEND_Y4)
        time.sleep(1.05)
        _buf = COMM.read_all()
        # na=np.array(_buf,dtype=np.byte)
        if _buf == b'\x820000\x03\xc33':
            print("e2")
            return 0
        print(len(_buf), _buf, bytes(READ_Y4_OFF), list(_buf))

import cv2
def ser_init():
    global COMM
    try:
        # speed=
        print(get_com_list())
        for a in port_list:
            print(a.device)
        cfg = cv2.FileStorage('config.yaml', cv2.FileStorage_READ)
        serial_port = cfg.getNode('com').string()
        cfg.release()
        COMM = serial.Serial(serial_port, 9600, timeout=0.1)
        if COMM.isOpen():
            print(serial_port, "open success")
        else:
            print("open failed")
            assert 0

    except serial.serialutil.SerialException as r:
        print(r)
        return
if __name__ == '__main__':
    print(get_com_list())
    for a in port_list:
        print(a.device)
    serial_port = "/dev/ttyUSB3"
    COMM = serial.Serial(serial_port, 9600, timeout=0.1)
    thread1 = threading.Thread(target=thread_com_receive)
    thread1.start()
    time.sleep(2.05)
    COMM.write(Y1_OFF)
    COMM.write(Y2_ON)
    time.sleep(2.05)
    COMM.write(Y2_OFF)
    COMM.write(Y1_ON)
    serial_close()
